import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
//创建一个二叉树，遍历整棵树，把所有元素打印出来
public class iterativeTreeNode {
    public static List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> Q = new LinkedList<>();
        if(root!=null){
            Q.offer(root);
        }
        List<List<Integer>> ans = new LinkedList<>();
        while(Q.size()>0){
            final int qSize=Q.size();
            List<Integer> tmp = new LinkedList<>();
            for(int i=0;i<qSize;i++){
                TreeNode cur = Q.poll();
                tmp.add(cur.val);
                if(cur.left!=null){
                    Q.offer(cur.left);
                }
                if(cur.right!=null){
                    Q.offer(cur.right);
                }

            }
            ans.add(tmp);
        }
        return ans;
    }



    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);
        TreeNode t6 = new TreeNode(21);
        TreeNode t7 = new TreeNode(17);
        TreeNode t8 = new TreeNode(10);
        TreeNode t9 = new TreeNode(2);

        t1.left=t2;
        t1.right=t3;

        t3.left=t4;
        t3.right=t5;

        t5.left=t6;
        t5.right=t7;

        t4.left=t8;
        t4.right=t9;

        List<List<Integer>> ans =  levelOrder(t1);
        System.out.println(Arrays.toString(ans.toArray()));

    }
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }


}
